﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.order
{
    public partial class orders : BaseAdmin
    {
        readonly DALOrderCompain theOrderCompain = new DALOrderCompain();
        readonly DALCompain theCompain = new DALCompain();
        readonly DALWarehouseGoodsOut theWarehouseGoodsOut = new DALWarehouseGoodsOut();
        readonly DALOrder theOrder = new DALOrder();
        // Fields
         string cardPoints = "0";
         string payPoints = "0";
         string sumPoints = "0";
         string yawnPoints = "0";
        

         StringBuilder _cardBaseInfo = new StringBuilder();

         public string CardBaseInfo
         {
             get { return _cardBaseInfo.ToString(); }
         }
         StringBuilder _cardPayInfo = new StringBuilder();

         public string CardPayInfo
         {
             get { return _cardPayInfo.ToString() ; }
          
         }
         StringBuilder _cardLogisticsInfo = new StringBuilder();

         public string CardLogisticsInfo
         {
             get { return _cardLogisticsInfo.ToString(); }
           
         }



        // Methods
        private void Bind()
        {
            string sql = "select orderid, ordercode, memberid, (select memberlogin from tbMember where memberid=DB_order.memberid) as memberlogin, pay, ship, cname, tel, phone, post, address, email, [content], cname1, tel1, phone1, post1, address1, email1, content1, states, "
                     + " ordertime, paytime, totalprice, cardprice, scoreprice, orderscore, isnull(cardid,0) as cardid, scoretype, SendCompany, SendCode, convert(varchar(10),senddate,111) as senddate, isnull(SendDate1,'') as TempSendDate1, "
                     + " SendUrl,SendTelphone,SendPerson,SendPersonCompany,SendPersonAddress "
                    + "  from DB_order where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
               
                _cardBaseInfo.AppendFormat("订单号：{0}<br/>", table.Rows[0]["ordercode"].ToString());


                string sStates = table.Rows[0]["states"].ToString();
                string StateName = "";

                if (sStates == "0")
                {
                    StateName = "新订单";
                }
                else if (sStates == "1")
                {
                    StateName = "备货中";
                }
                else if (sStates == "2")
                {
                    StateName = "已发货";
                }
                else if (sStates == "3")
                {
                    StateName = "已完成";
                }
                else if (sStates == "5")
                {
                    StateName = "已取消";
                }
                if (sStates != "5")
                {
                    this.ddlOrderStates.SelectedValue = sStates;
                }
                this.txtOrderRemark.Text = table.Rows[0]["content1"].ToString();

                _cardBaseInfo.AppendFormat("状态：{0}<br/>", StateName);
                _cardBaseInfo.AppendFormat("下单人：{0}<br/>", table.Rows[0]["cname"].ToString());
                _cardBaseInfo.AppendFormat("下单时间：{0}<br/>", table.Rows[0]["ordertime"].ToString());

                if (!string.IsNullOrEmpty(table.Rows[0]["memberid"].ToString()) && table.Rows[0]["memberid"].ToString() != "0")
                {
                    _cardBaseInfo.AppendFormat("支付方式：会员名({0})通过卡内福点数支付</br>", table.Rows[0]["memberlogin"].ToString());
                }
                else
                {
                    StringBuilder sUsedCards = new StringBuilder();
                    DataTable dtCards = new DataTable();
                    dtCards = SQLAccess.GreatDs("select c.* from DB_Order o join tbOrderAccount oa "
                                                 + " on o.OrderCode = oa.OrderCode "
                                                 + " join DB_Card c on oa.cardid = c.cardid "
                                                 + " where o.ordercode='" + table.Rows[0]["ordercode"].ToString() + "'").Tables[0];
                    int iRow = 0;
                    foreach (DataRow drCard in dtCards.Rows)
                    {
                        iRow++;
                        if (iRow % 5 == 0)
                        {
                            sUsedCards.Append( drCard["cardcode"].ToString() + "|\n");
                        }
                        else
                        {
                            sUsedCards.Append(drCard["cardcode"].ToString() + "|");
                        }
                    }
                    _cardBaseInfo.AppendFormat("支付方式：使用礼品卡号-{0}</br>", sUsedCards.ToString());
                }
                _cardBaseInfo.AppendFormat("订购说明：{0}</br>", table.Rows[0]["content1"].ToString());


                _cardLogisticsInfo.AppendFormat("物流公司：{0}<br/>", table.Rows[0]["SendCompany"].ToString());
                _cardLogisticsInfo.AppendFormat("物流单号：{0}<br/>",table.Rows[0]["SendCode"].ToString());
                _cardLogisticsInfo.AppendFormat("物流查询网址：<a href='{0}' target='_blank' >{0}</a><br/>", table.Rows[0]["SendUrl"].ToString());
                _cardLogisticsInfo.AppendFormat("物流查询电话：{0}<br/>", table.Rows[0]["SendTelphone"].ToString());
                _cardLogisticsInfo.AppendFormat("发货时间：{0}<br/>", table.Rows[0]["TempSendDate1"]);
                _cardLogisticsInfo.AppendFormat("寄件公司：{0}<br/>", table.Rows[0]["SendPersonCompany"].ToString());
                _cardLogisticsInfo.AppendFormat("寄件人：{0}<br/>", table.Rows[0]["SendPerson"].ToString());
                _cardLogisticsInfo.AppendFormat("寄件地址：{0}<br/>", table.Rows[0]["SendPersonAddress"].ToString());
  
                if ((table.Rows[0]["cardid"].ToString() != "0") && (table.Rows[0]["cardprice"].ToString() != "0"))
                {
                    DataTable table3 = SQLAccess.GreatDs("select cardcode from DB_Card where cardid=" + table.Rows[0]["cardid"].ToString() + "").Tables[0];
                    if (table3.Rows.Count > 0)
                    {
                       // this.shiptime.Text = "礼品卡卡号：" + table3.Rows[0]["cardcode"].ToString() + " 支付金额：" + table.Rows[0]["cardprice"].ToString();
                        this.cardPoints = table.Rows[0]["cardprice"].ToString();
                    }
    
                }

              
                if (table.Rows[0]["states"].ToString() == "0")
                {
                 
                    if (base.Request.QueryString["flag"] == "1")
                    {
                        this.txtSendAddress.Readonly = false;
                        this.txtCname.Readonly = false;

                        this.txtMobile.Readonly = false;
                        this.dpkSendTime.Readonly = false;
                        this.txtTel.Readonly = false;
                        this.btnUpdateAddress.Enabled = true;
                    }
                    else
                    {
                        this.txtSendAddress.Readonly = true;
                        this.txtCname.Readonly = true;

                        this.txtMobile.Readonly = true;
                        this.dpkSendTime.Readonly = true;
                        this.txtTel.Readonly = true;
                        this.btnUpdateAddress.Enabled = false;
                    }
                }
                else
                {
                    this.txtSendAddress.Readonly = true;
                    this.txtCname.Readonly = true;

                    this.txtMobile.Readonly = true;
                    this.dpkSendTime.Readonly = true;
                    this.txtTel.Readonly = true;
                    this.btnUpdateAddress.Enabled = false;
                }
               
                this.txtCname.Text = table.Rows[0]["cname1"].ToString();
                this.txtSendAddress.Text = table.Rows[0]["address1"].ToString();
                this.txtTel.Text = table.Rows[0]["tel1"].ToString();
                this.dpkSendTime.Text = DateTime.Parse(table.Rows[0]["sendDate"].ToString()).ToString("yyyy-MM-dd") ;
           
                this.txtMobile.Text = table.Rows[0]["phone1"].ToString();
           
                DataTable table5 = SQLAccess.GreatDs("select sum(DB_Car.goodsCount) as goodsCount," + table.Rows[0]["orderId"].ToString() + " as orderId," + table.Rows[0]["orderCode"].ToString() + " as orderCode,DB_Car.goodsPoints,sum(DB_Car.sumPoints ) as sumPoints,DB_Car.contents,tbGoods.typeid,tbGoods.goodsName,tbGoods.bigPic,tbGoods.changePoints,tbGoods.smallPic,tbGoods.goodsId   "
                         + ", isnull((select modelTypeName from tbModelType where modelTypeId = DB_Car.modelTypeId),'') as modelTypeName,isnull(DB_car.modelTypeId,0) as modelTypeId " 
                         + " from DB_Car inner join tbGoods on DB_Car.goodsId=tbGoods.goodsId "
                         + " where DB_Car.flag=1 and DB_Car.ordercode=" + table.Rows[0]["ordercode"].ToString()
                         + " group by DB_Car.goodsCount,DB_Car.goodsPoints,DB_Car.sumPoints,DB_Car.modelTypeId,DB_Car.contents,tbGoods.typeid,tbGoods.goodsName,tbGoods.changePoints,tbGoods.smallPic,tbGoods.goodsId,tbGoods.bigPic ").Tables[0];
                if (table5.Rows.Count > 0)
                {
                
                    this.Grid1.DataSource = table5;
                    this.Grid1.DataBind();
                }
                DataTable dtOrder = theOrder.GetList("orderCode='" + table.Rows[0]["orderCode"].ToString() + "'").Tables[0];
                foreach (DataRow row in dtOrder.Rows)
                {
                    this.sumPoints = (long.Parse(this.sumPoints) + long.Parse(row["totalPrice"].ToString())).ToString();
                    this.cardPoints = (long.Parse(this.cardPoints) + long.Parse(row["cardPrice"].ToString())).ToString();
                }

       

                this.yawnPoints = (long.Parse(this.sumPoints) - long.Parse(this.payPoints)  - long.Parse(this.cardPoints)).ToString() ;
            }
            _cardPayInfo.AppendFormat("商品小计：{0}<br/>", this.cardPoints);
            _cardPayInfo.AppendFormat("运费：{0}<br/>", long.Parse(this.sumPoints) -  long.Parse(this.cardPoints));
            _cardPayInfo.AppendFormat("使用卡福点数：{0}<br/>", this.sumPoints);
        }


 

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!base.IsPostBack )
            {
                this.BuildForm();
            }
        }

        void BuildForm()
        {
            if (base.Request.QueryString["oid"] != "")
            {
                this.Bind();
                this.BindCompainTypeList();
                this.BindCompain();
                if (base.Request.QueryString["flag"] == "1")
                {
                    this.panelOperate.Hidden = false;
                    this.panelCompain.Hidden = true;
                }
                else if (base.Request.QueryString["flag"] == "2")
                {
                    this.panelOperate.Hidden = true;
                    this.panelCompain.Hidden = false;
                }
                else
                {
                    this.panelOperate.Hidden = false;
                    this.panelCompain.Hidden = true;
                }
            }
        }

        void BindCompainTypeList()
        {
            DataSet ds;
            ds = theCompain.GetList("");
            if (ds != null && ds.Tables.Count > 0)
            {
                this.ddlCompainType.DataTextField = "CompainName";
                this.ddlCompainType.DataValueField = "CompainId";
                this.ddlCompainType.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompainType.DataBind();
                this.ddlCompainType.Items.Insert(0, new ExtAspNet.ListItem("投诉类别...", "-1"));
            }

            DB_Order oOrder;
            oOrder = new DALOrder().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
            if (oOrderCompain != null && oOrderCompain.CompainId != 0)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompainContent.Text = oOrderCompain.Content;
            }
        }



        private void BindCompain()
        {
            DB_Order oOrder;
            oOrder = new DALOrder().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
            if (oOrderCompain != null && oOrderCompain.CompainId != 0)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompainContent.Text = oOrderCompain.Content;
                this.txtCompainProcessRemark.Text = oOrderCompain.Process;
            }
        }


        protected void btnUpdateAddress_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime.Parse(this.dpkSendTime.Text);
            }
            catch
            {
                ExtAspNet.Alert.Show("送货日期格式不正确！");
                return; 
            }
            string strSql = "update DB_Order set address1='" + this.txtSendAddress.Text.Trim() +"'"
                           + ", cname1='" + this.txtCname.Text.Trim() +"'"
                           + ", sendDate='" + this.dpkSendTime.Text.Trim() + "'"
                           + ", tel1='" + this.txtTel.Text.Trim() + "'"
                           + ", phone1='" + this.txtMobile.Text.Trim() + "'"                  
                           + " where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            SQLAccess.DoSql(strSql);
            ExtAspNet.Alert.Show("保存成功！");
            this.BuildForm();

        }

        protected void btnSaveStatesRemark_Click(object sender, EventArgs e)
        {
            SQLAccess.DoSql("update DB_Order set states=" + this.ddlOrderStates.SelectedItem.Value + ",content1='" + re.replace(this.txtOrderRemark.Text) + "' where orderid=" + base.Request.QueryString["oid"] + "");
            ExtAspNet.Alert.Show("保存成功！");
            this.BuildForm();
        }


        protected void btnCompain_Click(object sender, EventArgs e)
        {
            DB_Order oOrder;
            oOrder = new DALOrder().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);

            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompainContent.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.AddDate = DateTime.Now;
                theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompainContent.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.AddDate = DateTime.Now;
                theOrderCompain.Update(oOrderCompain);
            }
            ExtAspNet.Alert.Show("保存成功！");
            this.BuildForm();
        }

        protected void btnCopainProcess_Click(object sender, EventArgs e)
        {
            DB_Order oOrder;
            oOrder = new DALOrder().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);

            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompainContent.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.Process = this.txtCompainProcessRemark.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompainContent.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.Process = this.txtCompainProcessRemark.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                theOrderCompain.Update(oOrderCompain);
            }

            ExtAspNet.Alert.Show("保存成功！");
            this.BuildForm();
        }


        protected void Window1_Close(object sender, EventArgs e)
        {
            this.BuildForm();
        }

        protected void Grid1_RowDataBound(object sender, ExtAspNet.GridRowEventArgs e)
        {

            if (!theWarehouseGoodsOut.IsOutWarehouse(long.Parse(Grid1.DataKeys[e.RowIndex][1].ToString()), int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString()), int.Parse(Grid1.DataKeys[e.RowIndex][2].ToString()),int.Parse(Grid1.DataKeys[e.RowIndex][3].ToString())))
            {
                Grid1.Rows[e.RowIndex].Values[5] = "";
            }

        }



    }
}